#include "ml307_json_cmd.h"

#include "ml307.h"
#include "ml307_parm.h"
#include "ml307_thread.h"

static bool ml_4g_get_callback(void *userarg, char *injsonstr, char *outjsonstr, size_t buffer_size);
                              
static bool ml_num_get_callback(void *userarg, char *injsonstr, char *outjsonstr, size_t buffer_size);
                              
static bool ml_num_set_callback(void *userarg, char *injsonstr, char *outjsonstr, size_t buffer_size);
                                
static bool ml_cfg_get_callback(void *userarg, char *injsonstr, char *outjsonstr, size_t buffer_size);
                               
static bool ml_cfg_set_callback(void *userarg, char *injsonstr, char *outjsonstr, size_t buffer_size);
                                
static bool ml_online_get_callback(void *userarg, char *injsonstr, char *outjsonstr,size_t buffer_size);

static bool ml_reg_set_callback(void *userarg, char *injsonstr, char *outjsonstr,size_t buffer_size);

static bool ml_reg_get_callback(void *userarg, char *injsonstr, char *outjsonstr,size_t buffer_size); 

static bool ml_mqtt_sta_get_callback(void *userarg, char *injsonstr, char *outjsonstr,size_t buffer_size);                               
/**
 * 示例指令表（用户可扩展）
 * EXT_CMD("NAME", xx_get_handler, xx_set_handler)
 * NAME: 指令名称 指令匹配字段
 * xx_get_handler
 * XX_set_handler
 */
static const jsonCommandEntry json_command_table[] = {
    EXT_JSON_CMD("ml_num_get", "get", ml_num_get_callback),
    EXT_JSON_CMD("ml_num_set", "set", ml_num_set_callback),
    EXT_JSON_CMD("ml_cfg_get", "get", ml_cfg_get_callback),
    EXT_JSON_CMD("ml_cfg_set", "set", ml_cfg_set_callback),
    EXT_JSON_CMD("ml_online_get","get", ml_online_get_callback),
    EXT_JSON_CMD("ml_4g_get","get", ml_4g_get_callback),
    EXT_JSON_CMD("ml_reg_set","set", ml_reg_set_callback),
    EXT_JSON_CMD("ml_reg_get","get",  ml_reg_get_callback),
    EXT_JSON_CMD("ml_mqtt_sta_get","get",  ml_mqtt_sta_get_callback),
};
static const jsonCommandEntry *find_command(const jsonCommandEntry *cmd_table, const char *name) {
    for (size_t i = 0; i < sizeof(json_command_table) / sizeof(jsonCommandEntry); i++) {
        if (strcasecmp(cmd_table[i].name, name) == 0) {
            return &cmd_table[i];
        }
    }
    return NULL;
}

/**
 * @brief 解析 JSON 字符串，提取 cmd 和 type
 * @param userarg 用户参数
 * @param cmd_buffer_t 输入的 JSON 字符串
 * @param response_t 输出缓冲区，存储提取的 cmd 字符串
 * @param len 输出缓冲区大小
 * @return 0 成功，-1 失败
 */

void ml370_json_cmd_switch(void *userarg, char *cmd_buffer_t, char *response_t, size_t len) {
    cJSON *json = cJSON_Parse(cmd_buffer_t);
    if (!json) {
        snprintf(response_t, 64, "Error parsing JSON");
        return;
    }

    // 解析 method
    cJSON *method = cJSON_GetObjectItem(json, "method");
    if (!method || !cJSON_IsString(method)) {
        snprintf(response_t, 64, "{\"erro\": \"erro_type\",\"erro_type\":2}");
        cJSON_Delete(json);
        return;
    }

    // 解析 cmd
    cJSON *cmd = cJSON_GetObjectItem(json, "cmd");
    if (!cmd || !cJSON_IsString(cmd)) {
        snprintf(response_t, 64, "{\"erro\": \"erro_type\",\"erro_type\":2}");
        cJSON_Delete(json);
        return;
    }
    // 查找指令
    const jsonCommandEntry *command = find_command(json_command_table, cmd->valuestring);
    if (command) {
        // 调用对应的处理函数
        if (command->json_callback) {
            command->json_callback(userarg, cmd_buffer_t, response_t, len);
        } else {
            snprintf(response_t, 64, "{\"erro\": \"erro_type\",\"erro_type\":1}");
        }
    } else {
        snprintf(response_t, 64, "{\"erro\": \"erro_type\",\"erro_type\":1}");
    }

    cJSON_Delete(json);
}
/**
 * @brief 处理4G配置获取的回调函数
 * @param userarg 用户参数(ml307_cfg_t结构体指针)
 * @param injsonstr 输入JSON字符串
 * @param outjsonstr 输出缓冲区
 * @param buffer_size 输出缓冲区大小
 * @return true 处理成功，false 处理失败
 */
bool cml_json_handler(const char *value, char *response, char *json_str) {
    printf("%s\r\n", json_str);
    ml370_json_cmd_switch(&ml307_cfg, json_str, response, 512);
    return 1;
}
// cb函数的编写
/**
 * @brief 4G配置获取回调函数
 * @param userarg 用户参数(ml307_cfg_t结构体指针)
 * @param injsonstr 输入JSON字符串
 * @param outjsonstr 输出缓冲区
 * @param buffer_size 输出缓冲区大小
 * @return true 处理成功，false 处理失败
 */
static bool ml_num_get_callback(void *userarg, char *injsonstr, char *outjsonstr,
                                size_t buffer_size) {
    // 创建根 JSON 对象
    cJSON *root = cJSON_CreateObject();
    if (root == NULL) {
        return 0;  // 创建失败
    }

    // 添加 "cmd" 和 "method" 键值对
    cJSON_AddStringToObject(root, "cmd", "ml_num_get");
    cJSON_AddStringToObject(root, "method", "get");

    // 创建 "arg" 对象
    cJSON *arg = cJSON_CreateObject();
    if (arg == NULL) {
        cJSON_Delete(root);  // 释放 root
        return 0;
    }
    ml307_cfg_t *cfg = (ml307_cfg_t *)userarg;
    // 添加 "mqttc_num" 键值对到 "arg"
    cJSON_AddNumberToObject(arg, "mqttc_num", cfg->ml307_mqttc_num);
    // 将 "arg" 添加到根对象
    cJSON_AddItemToObject(root, "arg", arg);

    cJSON_PrintPreallocated(root, outjsonstr, buffer_size, 0);
    // 释放 JSON 对象
    cJSON_Delete(root);
    return 1;
}

/**
 * @brief 设置MQTT客户端数量的回调函数
 * @param userarg 用户参数
 * @param injsonstr 输入JSON字符串
 * @param outjsonstr 输出缓冲区
 * @param buffer_size 输出缓冲区大小
 * @return true 处理成功，false 处理失败
 */
static bool ml_num_set_callback(void *userarg, char *injsonstr, char *outjsonstr,
                                size_t buffer_size) {
    // 1. 参数有效性检查
    if (!injsonstr || !outjsonstr || buffer_size < 64) {
        snprintf(outjsonstr, 64, "{\"error\":\"invalid_params\"}");
        return false;
    }

    // 2. 解析输入JSON
    cJSON *root = cJSON_Parse(injsonstr);
    if (!root) {
        snprintf(outjsonstr, 64, "{\"error\":\"parse_failed\"}");
        return false;
    }

    // 3. 验证必填字段
    cJSON *cmd = cJSON_GetObjectItem(root, "cmd");
    cJSON *method = cJSON_GetObjectItem(root, "method");
    cJSON *arg = cJSON_GetObjectItem(root, "arg");

    if (!cmd || !method || !arg || !cJSON_IsString(cmd) || !cJSON_IsString(method) ||
        !cJSON_IsObject(arg)) {
        cJSON_Delete(root);
        snprintf(outjsonstr, 64, "{\"error\":\"missing_fields\"}");
        return false;
    }

    // 4. 获取mqttc_num参数
    cJSON *mqttc_num = cJSON_GetObjectItem(arg, "mqttc_num");
    if (!mqttc_num || !cJSON_IsNumber(mqttc_num)) {
        cJSON_Delete(root);
        snprintf(outjsonstr, 64, "{\"error\":\"invalid_mqttc_num\"}");
        return false;
    }

    // 5. 验证数值范围 (1-4)
    int num = mqttc_num->valueint;
    if (num < 1 || num > 4) {
        cJSON_Delete(root);
        snprintf(outjsonstr, 64, "{\"error\":\"invalid_range\",\"valid_range\":\"1-4\"}");
        return false;
    }

    // 6. 更新结构体
    ml307_cfg_t *cfg = (ml307_cfg_t *)userarg;
    cfg->ml307_mqttc_num = num;

    // 7. 生成响应
    cJSON *response = cJSON_CreateObject();
    if (response) {
        cJSON_AddStringToObject(response, "cmd", "ml_num_set");
        cJSON_AddStringToObject(response, "method", "set");

        cJSON *arg_obj = cJSON_CreateObject();
        if (arg_obj) {
            cJSON_AddNumberToObject(arg_obj, "status", 1);  // 1表示成功
            cJSON_AddItemToObject(response, "arg", arg_obj);
        }

        cJSON_PrintPreallocated(response, outjsonstr, buffer_size, 0);
        cJSON_Delete(response);
    } else {
        snprintf(outjsonstr, 64,"{\"cmd\":\"ml_num_set\",\"method\":\"set\",\"arg\":{\"status\":1}}");
    }

    cJSON_Delete(root);
    return true;
}
// 6. 填充响应数据（使用安全字符串处理）
#define ADD_SAFE_STRING(field, value)               \
    if (value && value[0] != '\0')                  \
        cJSON_AddStringToObject(arg, field, value); \
    else                                            \
        cJSON_AddStringToObject(arg, field, "")
/**
 * @brief MQTT配置获取回调函数
 * @param userarg 用户参数(ml307_cfg_t结构体指针)
 * @param injsonstr 输入JSON字符串
 * @param outjsonstr 输出缓冲区
 * @param buffer_size 输出缓冲区大小
 * @return true 处理成功，false 处理失败
 */
static bool ml_cfg_get_callback(void *userarg, char *injsonstr, char *outjsonstr,
                                size_t buffer_size) {
    // 1. 参数有效性检查（增强版）
    if (!userarg || !injsonstr || !outjsonstr || buffer_size < 256) {
        if (outjsonstr && buffer_size > 0) {
            snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_params\"}");
        }
        return false;
    }

    // 2. 类型转换
    ml307_cfg_t *cfg = (ml307_cfg_t *)userarg;
    if (!cfg) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_config\"}");
        return false;
    }

    // 3. 解析输入JSON
    cJSON *root = cJSON_Parse(injsonstr);
    if (!root) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"parse_failed\"}");
        return false;
    }

    // 4. 获取并验证id_index
    cJSON *id_index = cJSON_GetObjectItemCaseSensitive(root, "id_index");
    if (!id_index || !cJSON_IsNumber(id_index)) {
        cJSON_Delete(root);
        snprintf(outjsonstr, buffer_size, "{\"error\":\"missing_id_index\"}");
        return false;
    }

    int index = id_index->valueint;
    if (index < 0 || index >= 4) {  // 假设最多4个配置
        cJSON_Delete(root);
        snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_index\",\"valid_range\":\"0-3\"}");
        return false;
    }

    // 5. 构建响应
    cJSON *response = cJSON_CreateObject();
    cJSON *arg = cJSON_CreateObject();
    if (!response || !arg) {
        if (response) cJSON_Delete(response);
        if (arg) cJSON_Delete(arg);
        cJSON_Delete(root);
        snprintf(outjsonstr, buffer_size, "{\"error\":\"memory_error\"}");
        return false;
    }
    cJSON_AddStringToObject(response, "cmd", "ml_cfg_get");
    cJSON_AddStringToObject(response, "method", "get");
    cJSON_AddNumberToObject(response, "id_index", index);

    // 填充配置参数
    cJSON_AddNumberToObject(arg, "mq_status", cfg->smqtt[index].mqttc_link);
    cJSON_AddNumberToObject(arg, "ssl_enable", cfg->smqtt[index].ssl);
    cJSON_AddNumberToObject(arg, "topic_mux_enable", cfg->smqtt[index].topic_mux);

    ADD_SAFE_STRING("ip_host", cfg->smqtt[index].host);
    ADD_SAFE_STRING("client_id", cfg->smqtt[index].client_id);
    ADD_SAFE_STRING("user_name", cfg->smqtt[index].user_name);
    ADD_SAFE_STRING("pass_word", cfg->smqtt[index].pass_word);
    ADD_SAFE_STRING("subtopic", cfg->smqtt[index].SubTopic[0].subtopic);
    ADD_SAFE_STRING("subtopic1", cfg->smqtt[index].SubTopic[1].subtopic);
    ADD_SAFE_STRING("subtopic2", cfg->smqtt[index].SubTopic[2].subtopic);
    ADD_SAFE_STRING("pubtopic", cfg->smqtt[index].PubTopic);

    cJSON_AddNumberToObject(arg, "port", cfg->smqtt[index].port);
    cJSON_AddNumberToObject(arg, "Qos", cfg->smqtt[index].Qos);

    cJSON_AddItemToObject(response, "arg", arg);

    // 7. 生成输出（带缓冲区检查）
    int needed = cJSON_GetArraySize(response) * 40 + 128;  // 预估所需空间
    if (needed > (int)buffer_size) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"output_overflow\",\"needed_size\":%d}",
                 needed);
        cJSON_Delete(response);
        cJSON_Delete(root);
        return false;
    }

    bool ret = cJSON_PrintPreallocated(response, outjsonstr, buffer_size, 0);
    if (!ret) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"output_failed\"}");
    }

    // 8. 清理资源
    cJSON_Delete(response);
    cJSON_Delete(root);
    return ret;
}
///////////////////////////////////////////////////////////////////////////////////////////
// 字符串字段处理（带安全截断）
#define SAFE_COPY(dest, src, size)      \
    do {                                \
        strncpy(dest, src, (size) - 1); \
        dest[(size) - 1] = '\0';        \
    } while (0)

/**
 * @brief MQTT配置设置回调函数
 * @param userarg 用户配置结构体指针
 * @param injsonstr 输入JSON字符串
 * @param outjsonstr 输出缓冲区
 * @param buffer_size 输出缓冲区大小
 * @return true 处理成功，false 处理失败
 */
static bool ml_cfg_set_callback(void *userarg, char *injsonstr, char *outjsonstr,
                                size_t buffer_size) {
    // 1. 参数校验（增强版）
    if (!userarg || !injsonstr || !outjsonstr || buffer_size < 128) {
        if (outjsonstr && buffer_size > 0) {
            snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_params\"}");
        }
        return false;
    }

    // 2. 类型转换
    ml307_cfg_t *cfg = (ml307_cfg_t *)userarg;
    bool ret = false;

    // 3. 解析JSON
    cJSON *root = cJSON_Parse(injsonstr);
    if (!root) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"parse_failed\"}");
        return false;
    }

    // 4. 校验必填字段
    cJSON *cmd = cJSON_GetObjectItemCaseSensitive(root, "cmd");
    cJSON *method = cJSON_GetObjectItemCaseSensitive(root, "method");
    cJSON *id_index = cJSON_GetObjectItemCaseSensitive(root, "id_index");

    if (!cmd || !method || !id_index || !cJSON_IsString(cmd) || !cJSON_IsString(method) ||
        !cJSON_IsNumber(id_index)) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"missing_fields\"}");
        goto cleanup;
    }

    // 5. 校验索引范围
    int index = id_index->valueint;
    if (index < 0 || index >= 4) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_index\",\"range\":\"0-3\"}");
        goto cleanup;
    }

    // 6. 处理arg字段
    cJSON *arg = cJSON_GetObjectItemCaseSensitive(root, "arg");
    if (!arg || !cJSON_IsObject(arg)) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_arg\"}");
        goto cleanup;
    }

    // 7. 解析各字段（使用安全宏）
    cJSON *ssl_enable = cJSON_GetObjectItemCaseSensitive(arg, "ssl_enable");
    cJSON *topic_mux = cJSON_GetObjectItemCaseSensitive(arg, "topic_mux_enable");
    cJSON *ip_host = cJSON_GetObjectItemCaseSensitive(arg, "ip_host");
    cJSON *port = cJSON_GetObjectItemCaseSensitive(arg, "port");
    cJSON *client_id = cJSON_GetObjectItemCaseSensitive(arg, "client_id");  // 修正拼写
    cJSON *user_name = cJSON_GetObjectItemCaseSensitive(arg, "user_name");
    cJSON *pass_word = cJSON_GetObjectItemCaseSensitive(arg, "pass_word");
    cJSON *subtopic = cJSON_GetObjectItemCaseSensitive(arg, "subtopic");
    cJSON *subtopic1 = cJSON_GetObjectItemCaseSensitive(arg, "subtopic1");
    cJSON *subtopic2 = cJSON_GetObjectItemCaseSensitive(arg, "subtopic2");
    cJSON *pubtopic = cJSON_GetObjectItemCaseSensitive(arg, "pubtopic");
    cJSON *qos = cJSON_GetObjectItemCaseSensitive(arg, "Qos");

    // 8. 更新配置（全部使用SAFE_COPY）
    if (ssl_enable && cJSON_IsNumber(ssl_enable)) {
        cfg->smqtt[index].ssl = ssl_enable->valueint ? 1 : 0;
    }
    if (topic_mux && cJSON_IsNumber(topic_mux)) {
        cfg->smqtt[index].topic_mux = topic_mux->valueint ? 1 : 0;
    }
    if (ip_host && cJSON_IsString(ip_host)) {
        SAFE_COPY(cfg->smqtt[index].host, ip_host->valuestring, sizeof(cfg->smqtt[index].host));
    }
    if (port && cJSON_IsNumber(port)) {
        cfg->smqtt[index].port = port->valueint;
    }
    if (client_id && cJSON_IsString(client_id)) {
        SAFE_COPY(cfg->smqtt[index].client_id, client_id->valuestring,
                  sizeof(cfg->smqtt[index].client_id));
    }
    if (user_name && cJSON_IsString(user_name)) {
        SAFE_COPY(cfg->smqtt[index].user_name, user_name->valuestring,
                  sizeof(cfg->smqtt[index].user_name));
    }
    if (pass_word && cJSON_IsString(pass_word)) {
        SAFE_COPY(cfg->smqtt[index].pass_word, pass_word->valuestring,
                  sizeof(cfg->smqtt[index].pass_word));
    }
    if (subtopic && cJSON_IsString(subtopic)) {
        SAFE_COPY(cfg->smqtt[index].SubTopic[0].subtopic, subtopic->valuestring,
                  sizeof(cfg->smqtt[index].SubTopic[0].subtopic));
    }
    if (subtopic1 && cJSON_IsString(subtopic1)) {  // 移除topic_mux条件判断
        SAFE_COPY(cfg->smqtt[index].SubTopic[1].subtopic, subtopic1->valuestring,
                  sizeof(cfg->smqtt[index].SubTopic[1].subtopic));
    }
    if (subtopic2 && cJSON_IsString(subtopic2)) {  // 移除topic_mux条件判断
        SAFE_COPY(cfg->smqtt[index].SubTopic[2].subtopic, subtopic2->valuestring,
                  sizeof(cfg->smqtt[index].SubTopic[2].subtopic));
    }
    if (pubtopic && cJSON_IsString(pubtopic)) {
        SAFE_COPY(cfg->smqtt[index].PubTopic, pubtopic->valuestring,
                  sizeof(cfg->smqtt[index].PubTopic));
    }
    if (qos && cJSON_IsNumber(qos)) {
        cfg->smqtt[index].Qos = (qos->valueint > 2) ? 0 : qos->valueint;
    }

    // 10. 生成响应（使用安全snprintf）
    int needed = snprintf(
        NULL, 0,
        "{\"cmd\":\"ml_cfg_set\",\"method\":\"set\",\"id_index\":%d,\"result\":\"success\"}",
        index);
    if (needed < 0 || (size_t)needed >= buffer_size) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"output_overflow\"}");
        goto cleanup;
    }
    snprintf(outjsonstr, buffer_size,
             "{\"cmd\":\"ml_cfg_set\",\"method\":\"set\",\"id_index\":%d,\"result\":\"success\"}",
             index);
    ret = true;

cleanup:
    if (root) cJSON_Delete(root);
    return ret;
}
/**
 * @brief 在线状态获取回调函数
 * @param userarg 用户参数(ml307_cfg_t结构体指针)
 * @param injsonstr 输入JSON字符串
 * @param outjsonstr 输出缓冲区
 * @param buffer_size 输出缓冲区大小
 * @return true 处理成功，false 处理失败
 */
static bool ml_online_get_callback(void *userarg, char *injsonstr, char *outjsonstr,
                                   size_t buffer_size) {
    // 创建根 JSON 对象
    cJSON *root = cJSON_CreateObject();
    if (root == NULL) {
        return 0;  // 创建失败
    }
    ml307_cfg_t *cfg = (ml307_cfg_t *)userarg;
    // 添加 "cmd" 和 "method" 键值对
    cJSON_AddStringToObject(root, "cmd", "ml_online_get");
    cJSON_AddStringToObject(root, "method", "get");

    // 创建 "arg" 对象
    cJSON *arg = cJSON_CreateObject();
    if (arg == NULL) {
        cJSON_Delete(root);  // 释放 root
        return 0;
    }
    // 添加 "mqttc_num" 键值对到 "arg"
    cJSON_AddNumberToObject(arg, "ml307_status", cfg->ml307_status);
    // 将 "arg" 添加到根对象
    cJSON_AddItemToObject(root, "arg", arg);

    cJSON_PrintPreallocated(root, outjsonstr, buffer_size, 0);
    // 释放 JSON 对象
    cJSON_Delete(root);
    return 1;
}
/**
 * @brief 4G信息获取回调函数
 * @param userarg 用户参数
 * @param injsonstr 输入JSON字符串
 * @param outjsonstr 输出缓冲区
 * @param buffer_size 输出缓冲区大小
 * @return true 处理成功，false 处理失败
 */
static bool ml_4g_get_callback(void *userarg, char *injsonstr, char *outjsonstr,
                               size_t buffer_size) {
    // 参数有效性检查
    if (!outjsonstr || buffer_size < 128) {
        return false;
    }

    // 1. 创建根JSON对象
    cJSON *root = cJSON_CreateObject();
    if (!root) {
        return false;
    }
    ml307_cfg_t *cfg = (ml307_cfg_t *)userarg;
    // 2. 添加固定字段
    cJSON_AddStringToObject(root, "cmd", "ml_4g_get");
    cJSON_AddStringToObject(root, "method", "get");

    // 3. 创建arg对象并填充数据
    cJSON *arg = cJSON_CreateObject();
    if (!arg) {
        cJSON_Delete(root);
        return false;
    }

    // 4. 从ml307_cfg结构体填充数据
    cJSON_AddStringToObject(arg, "imsi", cfg->ml307_net_info_t.imsi);
    cJSON_AddStringToObject(arg, "reg_ip", cfg->ml307_net_info_t.ip_4g);
    cJSON_AddStringToObject(arg, "iccid", cfg->ml307_net_info_t.iccid);
    cJSON_AddStringToObject(arg, "operator", cfg->ml307_net_info_t.net_name);
    cJSON_AddNumberToObject(arg, "rssi", cfg->ml307_net_info_t.db_singal);

    // 5. 组合JSON结构
    cJSON_AddItemToObject(root, "arg", arg);

    // 6. 序列化输出
    bool ret = cJSON_PrintPreallocated(root, outjsonstr, buffer_size, 0);
    if (!ret) {
        // 输出失败时提供错误信息
        snprintf(outjsonstr, buffer_size, "{\"error\":\"output_overflow\",\"required_size\":%d}",
                 (int)cJSON_GetArraySize(root) * 30);
    }

    // 7. 释放资源
    cJSON_Delete(root);
    return ret;
}

static bool ml_reg_set_callback(void *userarg, char *injsonstr, char *outjsonstr,size_t buffer_size){
        if (!injsonstr || !outjsonstr || buffer_size < 64) {
        snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_params\"}");
        }
        // 解析输入JSON
        cJSON *root = cJSON_Parse(injsonstr);
        if (!root) {
            snprintf(outjsonstr, buffer_size, "{\"error\":\"parse_failed\"}");
            return false;
        }
        // 获取cmd和method字段
        cJSON *cmd = cJSON_GetObjectItem(root, "cmd");
        cJSON *method = cJSON_GetObjectItem(root, "method");
        if (!cmd || !method || !cJSON_IsString(cmd) || !cJSON_IsString(method)) {
            cJSON_Delete(root);
            snprintf(outjsonstr, buffer_size, "{\"error\":\"missing_fields\"}");
            return false;
        }
        // 获取arg对象
        cJSON *arg = cJSON_GetObjectItem(root, "arg");
        if (!arg || !cJSON_IsObject(arg)) {
            cJSON_Delete(root);
            snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_arg\"}");
            return false;
        }
        // 获取各个字段
        cJSON *enable = cJSON_GetObjectItem(arg, "enable");
        cJSON *sp_time = cJSON_GetObjectItem(arg, "sp_time");
        if (!enable || !cJSON_IsNumber(enable) ||
            !sp_time || !cJSON_IsNumber(sp_time)) {
            cJSON_Delete(root);
            snprintf(outjsonstr, buffer_size, "{\"error\":\"missing_fields\"}");
            return false;
        }
        // 更新配置
        set_http_register_enable(enable->valueint);
        if(sp_time->valueint < 0 || sp_time->valueint > 3600) {
            cJSON_Delete(root);
            snprintf(outjsonstr, buffer_size, "{\"error\":\"invalid_sp_time\",\"valid_range\":\"10-3600\"}");
            return false;
        }
        uint16_t sp_time_value = (uint16_t)sp_time->valueint*(1000);
        set_sptime(sp_time_value);
        // 生成响应
        cJSON *response = cJSON_CreateObject();
        if (response) {
            cJSON_AddStringToObject(response, "cmd", "ml_reg_set");
            cJSON_AddStringToObject(response, "method", "set");

            cJSON *arg_obj = cJSON_CreateObject();
            if (arg_obj) {
                cJSON_AddNumberToObject(arg_obj, "op_status", 1);  // 1表示成功
                cJSON_AddItemToObject(response, "arg", arg_obj);
            }

            cJSON_PrintPreallocated(response, outjsonstr, buffer_size, 0);
            cJSON_Delete(response);
        } else {
            snprintf(outjsonstr, buffer_size,"{\"cmd\":\"ml_reg_set\",\"method\":\"set\",\"arg\":{\"op_status\":0}}");
        }
        cJSON_Delete(root);
        return true;   
}

static bool ml_reg_get_callback(void *userarg, char *injsonstr, char *outjsonstr,size_t buffer_size)
{
     // 参数有效性检查
    if (!outjsonstr || buffer_size < 128) {
        return false;
    }

    // 1. 创建根JSON对象
    cJSON *root = cJSON_CreateObject();
    if (!root) {
        return false;
    }
    // 2. 添加固定字段
    cJSON_AddStringToObject(root, "cmd", "ml_reg_get");
    cJSON_AddStringToObject(root, "method", "get");

    // 3. 创建arg对象并填充数据
    cJSON *arg = cJSON_CreateObject();
    if (!arg) {
        cJSON_Delete(root);
        return false;
    }

    // 4. 从ml307_cfg结构体填充数据
    cJSON_AddNumberToObject(arg, "ato_reg_en",get_http_register_enable());
    cJSON_AddNumberToObject(arg, "reg_sta", get_http_register_status());
    // 5. 组合JSON结构
    cJSON_AddItemToObject(root, "arg", arg);

    // 6. 序列化输出
    bool ret = cJSON_PrintPreallocated(root, outjsonstr, buffer_size, 0);
    if (!ret) {
        // 输出失败时提供错误信息
        snprintf(outjsonstr, buffer_size, "{\"error\":\"output_overflow\",\"required_size\":%d}",
                 (int)cJSON_GetArraySize(root) * 30);
    }

    // 7. 释放资源
    cJSON_Delete(root);
    return ret;
}

static bool ml_mqtt_sta_get_callback(void *userarg, char *injsonstr, char *outjsonstr,size_t buffer_size)
{
     // 参数有效性检查
    if (!outjsonstr || buffer_size < 128) {
        return false;
    }

    // 1. 创建根JSON对象
    cJSON *root = cJSON_CreateObject();
    if (!root) {
        return false;
    }
    // 2. 添加固定字段
    cJSON_AddStringToObject(root, "cmd", "ml_mqtt_sta_get");
    cJSON_AddStringToObject(root, "method", "get");

    // 3. 创建arg对象并填充数据
    cJSON *arg = cJSON_CreateObject();
    if (!arg) {
        cJSON_Delete(root);
        return false;
    }

    // 4. 从ml307_cfg结构体填充数据
    cJSON_AddNumberToObject(arg, "mq_sta0",get_ml307_mqttc_link(0));
    //cJSON_AddStringToObject(arg, "mq_sta1", get_http_register_status());
    //cJSON_AddStringToObject(arg, "mq_sta1", get_http_register_status());
    // 5. 组合JSON结构
    cJSON_AddItemToObject(root, "arg", arg);

    // 6. 序列化输出
    bool ret = cJSON_PrintPreallocated(root, outjsonstr, buffer_size, 0);
    if (!ret) {
        // 输出失败时提供错误信息
        snprintf(outjsonstr, buffer_size, "{\"error\":\"output_overflow\",\"required_size\":%d}",
                 (int)cJSON_GetArraySize(root) * 30);
    }
    // 7. 释放资源
    cJSON_Delete(root);
    return ret;
}
//josn对接

